package net.qqxh.common.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;

/**
 * @author jason
 */
public class TxtCharsetUtil {


    /**
     * 转换文本文件编码为utf8
     * 探测源文件编码,探测到编码切不为utf8则进行转码
     *
     * @param filePath 文件路径
     */
    public static void convertTextPlainFileCharsetToUtf8(String filePath, String topath) throws IOException {
        File sourceFile = new File(filePath);
        if (sourceFile.exists() && sourceFile.isFile() && sourceFile.canRead()) {
            String encoding = null;
            encoding = FileAnalysisTool.guessFileEncoding(sourceFile);
            if (encoding != null && !"UTF-8".equals(encoding)) {
                // 不为utf8,进行转码
                File tmpUtf8File = new File(topath);
                File pf = new File(tmpUtf8File.getParent());
                if (!pf.exists()) {
                    pf.mkdirs();
                }
                Writer writer = null;
                Reader reader = null;
                try {
                    writer = new OutputStreamWriter(new FileOutputStream(tmpUtf8File), "UTF-8");
                    reader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile), encoding));
                    char[] buf = new char[1024];
                    int read;
                    while ((read = reader.read(buf)) > 0) {
                        writer.write(buf, 0, read);
                    }
                } finally {
                    IOUtils.closeQuietly(reader);
                    IOUtils.closeQuietly(writer);
                }


            } else {
                FileUtils.copyFile(new File(filePath), new File(topath));
            }
        }
    }

    ;
}
